package com.monkeyk.sos.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.monkeyk.sos.domain.model.AdminDetails;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.service.AdminService;

@Service("adminService")
public class AdminServiceImpl implements AdminService {

	@Autowired
	private JdbcTemplate	jdbcTemplate;

	@Override
	public User findUserByAdminName(String adminName) {
		String sqlApp = " select * from administrator where  admin_name = ?";
		java.util.List<AdminDetails> adminDetailsList = this.jdbcTemplate.query(sqlApp, new Object[] { adminName },
				new RowMapper<AdminDetails>() {
					@Override
					public AdminDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
						AdminDetails adminDetails = new AdminDetails();
						adminDetails.setAdminId(rs.getLong("id"));
						adminDetails.setAdminName(rs.getString("admin_name"));
						adminDetails.setPassword(rs.getString("password"));
						adminDetails.setStatus(rs.getInt("status"));
						return adminDetails;
					}
				});
		User user = null;
		if (!adminDetailsList.isEmpty()) {
			user = adminDetailsList.get(0).createUser();
			user.privileges().addAll(findAdminPrivilege(adminDetailsList.get(0).getAdminId().intValue()));
		}
		return user;
	}
    /*
     * 查询权限信息
     */
    private Collection<Privilege> findAdminPrivilege(int adminId) {
		final String sql = " select privilege from admin_privilege where admin_id = ? ";
		final List<String> strings = this.jdbcTemplate.queryForList(sql, new Object[] { adminId }, String.class);
		List<Privilege> privileges = new ArrayList<Privilege>(strings.size());
		for (String string : strings) {
			privileges.add(Privilege.valueOf(string));
		}
		return privileges;
	}
}
